package com.k7k7.sserver.client;

import com.k7k7.sserver.room.Room;
import com.k7k7.sserver.room.RoomMgr;
import com.k7k7.util.ElementUtil;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * User: Administrator
 * Date: 2009-4-27
 * Time: 15:00:26
 */
public class RoomOpt extends Opt {
	private ClientS client;
	public Room room;

	public RoomOpt(ClientS clientS) {
		super();
		client = clientS;
	}

	public void quit() {
		if (room == null) {
			return;
		}
		Element re = DocumentHelper.createElement(UserCmd.tag_msg);
		re.addAttribute(UserCmd.tag_cmd, UserCmd.scene_other_leave);
		re.add(DocumentHelper.createElement("user").addAttribute(UserCmd.tag_uid,
				this.client.user.getId().toString()));
		this.room.remove(this.client);
		room.sendToAllClients(re);
		this.room = null;
	}

	protected void entered(Element cmd) {
		ElementUtil.removeAllChild(cmd);
		for (ClientS u : room.getAllClients()) {
			Element ue = DocumentHelper.createElement("user");
			ue.add(DocumentHelper.createAttribute(ue, "uid", u.user.getId().toString()));
			cmd.add(ue);
			Element baseinfo = DocumentHelper.createElement("baseinfo");
			u.userOpt.getInfo(baseinfo);
			ue.add(baseinfo);
			Element wear = DocumentHelper.createElement("wear");
			u.userOpt.getWear(wear);
			ue.add(wear);
		}
		client.send(cmd);
		//
		//
		Element p = DocumentHelper.createElement(UserCmd.tag_msg).addAttribute(UserCmd.tag_cmd,
				"scene_other_enter");
		Element uee = DocumentHelper.createElement("user");
		uee.add(DocumentHelper.createAttribute(uee, "uid", this.client.user.getId().toString()));
		p.add(uee);
		Element baseinfo = DocumentHelper.createElement("baseinfo");
		this.client.userOpt.getInfo(baseinfo);
		uee.add(baseinfo);
		Element wear = DocumentHelper.createElement("wear");
		this.client.userOpt.getWear(wear);
		uee.add(wear);
		//
		this.room.sendToAllClients(p);
		this.client.isReady = true;
	}

	protected void request_enter(Element cmd) {
		if (cmd.attribute("sceneid") == null) {
			return;
		}
		ElementUtil.removeAllChild(cmd);
		Room s = RoomMgr.getInstance().getRoomByID(cmd.attribute("sceneid").getStringValue());
		if (s != null && s.canEnter()) {
			cmd.add(DocumentHelper.createAttribute(cmd, "result", "1"));
			this.quit();
			this.room = s;
			this.client.isReady = false;
			s.add(this.client);
		} else {
			Room sc = RoomMgr.getInstance().getRoomCanEnter();
			cmd.add(DocumentHelper.createAttribute(cmd, "result", "0"));
			cmd.add(DocumentHelper.createAttribute(cmd, "recommand", sc
					.getRoomID()));
		}
		this.client.send(cmd);
	}
}
